package cn.tedu;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Author：程Sir
 * Name： redis-jedis
 * Content:
 */
public class JedisPoolUtils {
    private static JedisPool pool = null;
    static {
        //1. 获取输入流
        InputStream inputStream = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        //2.创建properties对象
        Properties properties = new Properties();
        //3.使用properties对象加载io流
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 4.获取配置数据
        String host = properties.getProperty("jedis.url");
        int port = Integer.valueOf(properties.getProperty("jedis.port"));
        int maxTotal = Integer.valueOf(properties.getProperty("jedis.maxTotal"));
        int maxIdle = Integer.valueOf(properties.getProperty("jedis.maxIdle"));
        System.out.println(host+", "+port+", "+maxTotal +", "+maxIdle);

        // *5.创建jedis连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 5.1 设置策略参数
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxIdle(maxIdle);
        // *6. 创建jedis连接池对象
        pool = new JedisPool(poolConfig, host, port);


    }

    /**
     * 获取jedis链接对象
     * @return 返回jedis链接池中空闲的jedis对象
     */
    public static Jedis getJedis(){
        // 6.1 从jedis连接池中获取jedis的链接对象
        return pool.getResource();
    }

    /**
     * 将使用后的jedis对象归还到jedis链接池中
     * @param jedis 要被归还的jedis对象
     */
    public static void closeJedis(Jedis jedis){
        // 6.2 将使用结束后的jedis对象归还给连接池
        jedis.close();
    }

    public static void main(String[] args) {
        System.out.println(pool);
        System.out.println(getJedis());
    }
}
